# -*- encoding: utf-8 -*-
# ePhorte parser
# e.g. http://www.gjerdrum.kommune.no/Modules/journal.aspx?Query=RecordDate%3a(-3)
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging, re
import datetime
from time import strptime
import BeautifulSoup
import jeje.parser

class parser(jeje.parser.ejeje_parser):
    def parse_enkeltjournal(self, suppe, uri):
        logging.info('starter ePhorte-relativ-parser')
        logging.debug('finner tittelposter i suppa')
        _tittelposter = suppe.findAll('div', {'class':'DetailView Postliste'})
        logging.debug('fant %d titler', len(_tittelposter))
        for i, tp in enumerate(_tittelposter):
            #<div class="DetailView Postliste">
            #<div class="Group">
            #<span class="Element"><span class="Content"><a title="&amp;Vis" href="/Modules/journaldocument.aspx?ObjectType=ePhorteRegistryEntry&amp;ePhorteRegistryEntry.ID=17274">
            #<h2 class="">
                                                                            #Oversendelse av avtale mellom GRIB og NRBR
            
                                                                    #</h2>
            #</a></span></span>
            #</div>
            #<div class="Group">
            #<span class="Element">
            #<h3>
            #<span>Dok.type</span>
            #</h3>
            #<span class="Content"><span>Inngående brev</span></span></span>
            #<span class="Element">
            #<h3>
            #<span>Journ.dato</span>
            #</h3>
            #<span class="Content"><span>03.10.2007</span></span></span>
            #<span class="Element">
            #<h3>
            #<span>Avs/Mot</span>
            #</h3>
            #<span class="Content"><span>Gardermoregionens Interkommunale Brannvesen IKS</span></span></span>
            #<span class="Element">
            #<h3>
            #<span>Tilhører sak</span>
            #</h3>
            #<span class="Content"><span>2006/132 Diverse skriv vedr. Gardermoregionens interkommunale brannvesen IKS, GRIB</span></span></span>
            #</div>
            #</div>
            j = 0
            elementer = tp.findAll('span', {'class':'Content'})
            overskrifter = [b.span.string for b in tp.findAll('h3')]
            _tittel = elementer[j].next #self.trekk_ut_streng(elementer[j])
            j+=1
            sok = elementer[j].findAll('a')
            if sok:
                _dok_uri = sok[1]['href']
                j += 1
            else:
                _dok_uri = None
            _retning = elementer[j].next
            j += 1
            _journaldato = elementer[j].next
            j += 1
            if overskrifter.count(u'Avs/Mot'):
                _adressat = elementer[j].next
                j += 1
            else:
                _adressat = None
            if overskrifter.count(u'Hjemmel'):
                _hjemmel = elementer[j].next
                j += 1
            else:
                _hjemmel = None
            _sakskompleks = elementer[j].next
 
            logging.debug('arbeider med post #%d: %s', i+1, _tittel.h2.string.strip())
            #for x in _retning, _journaldato, _adressat, _hjemmel, _sakskompleks:
                #print "-"*10, repr(x), "?"*5
            post = self.legg_til_post()
            post.sett_tittel(unicode(_tittel.h2.string.strip()))
            post.sett_uri(self.absoluttifiser(_tittel['href'], uri))
            if _dok_uri is not None:
                post.sett_dok_uri(self.absoluttifiser(_dok_uri, uri))
            if _adressat is not None:
                post.sett_adressat(unicode(_adressat.next))
            if _retning == u'Saksframlegg/innstilling':
                post.sett_kommentar(u'Saksframlegg/innstilling')
            post.sett_arkivdato(datetime.datetime(*strptime(_journaldato.next, '%d.%m.%Y')[0:6]))
            if isinstance(_sakskompleks, BeautifulSoup.NavigableString):
                post.sett_sakskompleks(unicode(_sakskompleks))
            else:
                try:
                    post.sett_sakskompleks(self.trekk_ut_streng(_sakskompleks))
                except AttributeError:
                    pass
            try:
                arkivsaksnr = post.sakskompleks.split()[0]
                if '/' in arkivsaksnr: 
                    post.sett_arkivsaksnr(arkivsaksnr)
            except: 
                pass # ingen saksnr i teksten
            if _hjemmel is not None:
                post.sett_lovreferanse(unicode(_hjemmel.next))
                post.sett_offentlig(False)
                logging.debug("Lovref: %s", post.lovreferanse)
            post.sett_refnr(post.uri.split('&ePhorteRegistryEntry.ID=')[1])
            post.sett_retning(unicode(_retning.next[0]))
            post.kontroller_felter()
        return self.journalposter

    def finn_enkeltjournal_uri(self, postjournal, suppe, dato=None):
        if dato is None:
            diff = postjournal.etterslep
            dato = datetime.date.today() - datetime.timedelta(days=diff)
        else:
            assert(isinstance(dato, datetime.date))
            diff = (datetime.date.today() - dato).days
        return unicode(postjournal.enkeltjournal_uri % (diff)), dato
        
